function SearchData(opt) {
	var options = {
		btn: '', // 点击请求数据的btn
		filterBtn: '',
		confirmBtn: '', 
		parentElem: 'body', // 
		condition: [],
		url: '',
		type: 'checkbox',
		checked: false,  // 是否默认全部选中
		rebuildTable: function() {},
		callback: function() {}, // 过滤数据之后的回调
	};

	this.opt = $.extend({}, options, opt);
	if (typeof this.opt.condition == 'string') {
		this.opt.condition = [this.opt.condition];
	}

	this.data = []; // 全部的数据
	this.result = []; // 过滤筛选之后的数据
	this.init();
}

SearchData.prototype.init = function() {
	this.eventInit();
};

// 事件绑定
SearchData.prototype.eventInit = function() {
	var _this = this;
	
	$(this.opt.btn).on('click', function() { 
		console.log('32131');
		_this.ajaxData();
	});

	$(this.opt.filterBtn).on('click', function() {
		var val = $.trim($(this).siblings('input').val());
		_this.filterData(val); 
		_this.opt.rebuildTable(_this.result);
	}); 
 
	$(this.opt.confirmBtn).on('click', function() { 
		_this.opt.callback(_this.result);
	});

	// 绑定check-one变化
	$(this.opt.parentElem).on('change', '.check-one', function() {
		var key = $(this).data('key'),
			checked = $(this).prop('checked');

		if (_this.opt.type == 'radio') { 
			$.each(_this.data, function(i, val) {
				val.checked = false;
			});
		} 
		_this.result[key].checked = checked;
	});

	// 绑定check-all变化
	$(this.opt.parentElem).on('change', '.check-all', function() {
		var key = $(this).data('key'),
			checked = $(this).prop('checked');
		
		$.each(_this.data, function(data) {
			data.checked = checked;
		});
	});
};

// ajax请求拿到全部数据
SearchData.prototype.ajaxData = function(obj) {
	if (this.data.length > 0) {
		this.result = this.data;
		this.opt.rebuildTable(this.result);
		return;
	}

	var data = obj || {},
		_this = this;
 
	$.post(this.opt.url, {keyword: ''}, function(json) {
		json = JSON.parse(json);
		_this.data = json;
		_this.addChecked();
		_this.result = _this.data;
		_this.opt.rebuildTable(_this.result);
	});
};

// 为所有数据增加一个选中的标记
SearchData.prototype.addChecked = function() {
	if (this.data.length <= 0) return;

	var _this = this;

	$.each(this.data, function(n, data) {
		data.checked = _this.opt.checked; 
	});
};

// 筛选数据
SearchData.prototype.filterData = function(val) {
	var _this = this,
		reg = new RegExp(val);

	if (!val) {
		this.result = this.data;
		return;
	}

	this.result = [];

	$.each(this.data, function(n, data) {
		for (var i = 0, cond; i < _this.opt.condition.length; i++) {
			cond = _this.opt.condition[i];

			if (cond in data && reg.test(data[cond])) {
				_this.result.push(data);
				break;
			} 
		}
	});
};

// 外部调用， 通过id更改数据的checked数据
SearchData.prototype.delDataById = function(id) {
	if (!id) return;
	var _this = this;
	$.each(this.data, function(n, data) {
		if (data.id == id) {
			data.checked = false;
			console.log(_this.data);
			return false;
		}
	});
};



